# -*- coding: utf-8 -*-
import traceback
import datetime
import hashlib
from utils.backcode import ImportError
from app.manage.userManage.common.manage_sql import UserManageSql
from utils.logger import Md_Debug
from utils.db_utils import DbConn


class UserEditeDB(object):
    """游戏管理"""
    
    def __init__(self):
        self.db = DbConn()
        self.nowtime = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
    
    def creat_user(self, body):
        """创建用户"""
        try:
            creatUser = dict()
            db = DbConn()
            # 0:创建 1：删除
            oper_type = body.get('oper_type', None)
            if oper_type == "0":
                user_name = body.get('user_name', None)
                user_passwd = body.get('user_passwd', None)
                company_post = body.get("compang_post", None)
                partment = body.get("partment", None)
                sysrole = body.get("sysrole", None)
                
                # check parameter
                if not user_name:
                    code = ImportError.IMPORT_CODE_INVALID_ARGS
                    message = "user_name is none"
                elif not user_passwd:
                    code = ImportError.IMPORT_CODE_INVALID_ARGS
                    message = "user_passwd is none"
                elif not company_post:
                    code = ImportError.IMPORT_CODE_INVALID_ARGS
                    message = "company_post is none"
                elif not partment:
                    code = ImportError.IMPORT_CODE_INVALID_ARGS
                    message = "partment is none"
                elif not sysrole:
                    code = ImportError.IMPORT_CODE_INVALID_ARGS
                    message = "sysrole is none"
                else:
                    query_back = db.fetch_one(UserManageSql.QUERY_USER, [user_name])
                    if query_back:
                        code = ImportError.IMPORT_CODE_INVALID_ARGS
                        message = "用户已经存在"
                    else:
                        user_passwd = hashlib.sha256(user_passwd).hexdigest()
                        param = [user_name, user_passwd, self.nowtime, 0, sysrole, company_post, partment]
                        db.commit(UserManageSql.CREAT_USER, param)
                        code = ImportError.IMPORT_CODE_SUCCESS
                        message = "success"
            elif oper_type == "1":
                user_id = body.get('user_id', None)
                
                # check parameter
                if not user_id:
                    code = ImportError.IMPORT_CODE_INVALID_ARGS
                    message = "user_id is none"
                else:
                    back_data = db.fetch_one(UserManageSql.USR_IS_ADMIN, [user_id])
                    if back_data['role_name'] == "超级管理员":
                        code = ImportError.IMPORT_CODE_INVALID_ARGS
                        message = "没有删除超级管理员权限"
                    else:
                        db.commit(UserManageSql.DELETE_USR, [user_id])
                        code = ImportError.IMPORT_CODE_SUCCESS
                        message = "success"
            else:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "Invalid parameter"
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        creatUser['response_code'] = code
        creatUser['response_msg'] = message
        return creatUser
    
    def re_passwd(self, body):
        """重置密码"""
        try:
            rePasswd = dict()
            db = DbConn()
            user_id = body.get('user_id', None)
            user_passwd = body.get('user_passwd', None)
            user_name = body.get('user_name', None)
            old_password = body.get('old_password', None)
            
            # check parameter
            if not user_id:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "user_id is none"
            elif not user_passwd:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "user_passwd is none"
            elif not old_password:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "user_passwd is none"
            elif not user_name:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "user_passwd is none"
            else:
                query_back = db.fetch_one(UserManageSql.QUERY_USER_PASS, [user_name,old_password,user_id])
                if query_back:
                    user_passwd = hashlib.sha256(user_passwd).hexdigest()
                    param = [user_passwd, self.nowtime, user_id]
                    db.commit(UserManageSql.RESRT_PASSWD, param)
                    code = ImportError.IMPORT_CODE_SUCCESS
                    message = "success"
                else:
                    code = ImportError.IMPORT_CODE_INVALID_ARGS
                    message = "error"
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        rePasswd['response_code'] = code
        rePasswd['response_msg'] = message
        return rePasswd
    
    def add_permit(self, body):
        """添加用户权限"""
        try:
            addPermit = dict()
            db = DbConn()
            user_id = body.get('user_id', None)
            menu_id = body.get('menu_id', None)
            # check parameter
            if not user_id:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "user_id is none"
            elif not menu_id:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "menu_id is none"
            else:
                db.commit(UserManageSql.UPDATE_ONE, [user_id])
                for i in range(len(menu_id)):
                    param = [user_id, menu_id[i]]
                    query_back = db.fetch_one(UserManageSql.QUERY_PERMIT, param)
                    if not query_back:
                        db.commit(UserManageSql.ADD_PERMIT, param)
                        code = ImportError.IMPORT_CODE_SUCCESS
                        message = "success"
                    else:
                        db.commit(UserManageSql.UPDATE_ONE_PERMIT, param)
                        code = ImportError.IMPORT_CODE_SUCCESS
                        message = "success"
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        addPermit['response_code'] = code
        addPermit['response_msg'] = message
        return addPermit
    
    def update_passwd(self, body):
        """修改密码"""
        try:
            updatePasswd = dict()
            db = DbConn()
            user_name = body.get('user_name', None)
            user_passwd = body.get('user_passwd', None)
            new_passwd = body.get('new_passwd', None)
            
            # check parameter
            if not user_name:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "user_name is none"
            elif not user_passwd:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "user_password is none"
            elif not new_passwd:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "new_passwd is none"
            else:
                # query old password
                user_passwd_old = hashlib.sha256(user_passwd).hexdigest()
                param = [user_name, user_passwd_old]
                query_back = db.fetch_one(UserManageSql.SELECT_OLD_PASSWD, param)
                if not query_back:
                    code = ImportError.IMPORT_CODE_INVALID_ARGS
                    message = "原密码输入错误"
                elif user_passwd == new_passwd:
                    code = ImportError.IMPORT_CODE_INVALID_ARGS
                    message = "输入密码与原密码一致"
                else:
                    user_passwd_new = hashlib.sha256(new_passwd).hexdigest()
                    param = [user_passwd_new, self.nowtime, user_name]
                    db.commit(UserManageSql.UPDATE_PASSWD, param)
                    code = ImportError.IMPORT_CODE_SUCCESS
                    message = "success"
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        updatePasswd['response_code'] = code
        updatePasswd['response_msg'] = message
        return updatePasswd
    
    def show_checked(self, body):
        """用户权限"""
        try:
            showChecked = dict()
            user_id = body.get('user_id', None)
            db = DbConn()
            
            # check parameter
            if not user_id:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "user_id is none"
            else:
                checked_back = db.fetch_all(UserManageSql.SHOW_CHECKED, [user_id])
                cloum_back = db.fetch_all(UserManageSql.CLOUM)
                for i in range(len(checked_back)):
                    for i1 in range(len(cloum_back)):
                        if checked_back[i]['id'] == cloum_back[i1]['id']:
                            cloum_back[i1]['checked'] = True
                code = ImportError.IMPORT_CODE_SUCCESS
                message = cloum_back
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        showChecked['response_code'] = code
        showChecked['response_msg'] = message
        return showChecked
